package com.zhulanhua.blogs.service.impl;

import com.zhulanhua.blogs.Utils.*;
import com.zhulanhua.blogs.dao.ImageDao;
import com.zhulanhua.blogs.domain.Image;
import com.zhulanhua.blogs.exception.BusinessException;
import com.zhulanhua.blogs.service.ImagesService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Log4j2
@Service
public class ImagesServiceImpl implements ImagesService {

    @Autowired
    ImageDao imageDao;
    @Autowired
    PathUtils pathUtils;

    @Autowired
    private Base64Utils base64Util;
    // 对字节数组字符串进行Base64解码并生成图片
    //imgFilePath 待保存的本地路径
    @Override
    public String GenerateImage(String base64Str){
        String date = DateUtils.dateToString(new Date(), "yyyy-MM-dd");
        String path = pathUtils.imagesPath + "\\" + date;
        String name = base64Util.GenerateImage(base64Str, path);
        return (path + "\\" + name).replace("\\","/");
    }

    @Override
    public List<Image> save(String[] base64) {
        ArrayList<Image> images = new ArrayList<>();
        for (String s : base64){
            Image image = new Image();
            image.setSrc(GenerateImage(s).replace("\\", "/"));
            int insert = imageDao.insert(image);
            if (insert != 1){
                new BusinessException(Code.BUSINESS_ERR, "批量保存路劲到数据库失败");
            }
            images.add(image);
        }
        return images;
    }
}



